package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.Problem;
import dao.ProblemDAO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 该类是操作题目相关的功能
 * 1、获取题目详情
 * 2、获取题目列表
 * 两个功能主要是根据请求当中是否有id来区分；
 */
@WebServlet("/problem")
public class ProblemServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setStatus(200);
        //根据ContentType来设置响应体的body部分数据类型
        resp.setContentType("application/json;charset=utf8");

        ProblemDAO problemDAO = new ProblemDAO();
        /*
        尝试获取 id 参数.
        如果能获取到, 说明是获取题目详情;
         如果不能获取到, 说明是获取题目列表.
         */
        String idString = req.getParameter("id");
        //没有id  根据API的设计，这就是查找题目列表
        if (idString == null || "".equals(idString)) {
            List<Problem> problems = problemDAO.selectAll();
            String respString = objectMapper.writeValueAsString(problems);
            //设置body里面的数据
            resp.getWriter().write(respString);
        } else {
            //有id  根据API的设计，这就是查找题目的详细信息
            Problem problem = problemDAO.selectOne(Integer.parseInt(idString));
            String respString = objectMapper.writeValueAsString(problem);
            //设置body里面的数据
            resp.getWriter().write(respString);
        }

    }
}
